import axios from 'axios'
import store from '../util/storeManage'
// qs模块
// import qs from 'qs'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const instance = axios.create({
  baseURL: 'http://127.0.0.1:5000' // http://172.16.40.30:5000
})

instance.interceptors.request.use(config => {
  NProgress.start()
  const tk = store.get('t_k') // 从本地取出token
  // 请求头统一携带token
  if (tk) {
    config.headers.Authorization = tk
  }
  return config
})

instance.interceptors.response.use(data => {
  NProgress.done()
  return data
})

export function Ajax (url, params = {}, type = 'GET') {
  return new Promise((resolve, reject) => {
    if (type.toUpperCase() === 'GET') {
      instance
        .get(url, { params })
        .then(res => {
          resolve(res.data)
        })
        .catch(r => {
          resolve(r)
        })
    } else if (type.toUpperCase() === 'POST') {
      instance
        // .post(url, qs.stringify(params))
        .post(url, params)
        .then(res => {
          resolve(res.data)
        })
        .catch(r => {
          resolve(r)
        })
    } else {
      reject(new Error({ code: '0', msg: '请求格式不正确!' }))
    }
  })
}
